package com.ff.kvm.config.filter;

import com.ff.kvm.common.eunm.StatusEnum;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.service.RedisService;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AuthFilter implements Filter {

    private RedisService redisService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.redisService = WebApplicationContextUtils.getRequiredWebApplicationContext(filterConfig.getServletContext()).getBean(RedisService.class);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;

        if (!checkLogin(request)) {
            Response response = new Response();
            response.setCode(StatusEnum.RE_LOGIN.code());
            response.setMsg(StatusEnum.RE_LOGIN.description());
            HttpServletResponse rep = (HttpServletResponse)servletResponse;
            rep.setHeader("Content-type", "charset=UTF-8");
            rep.getWriter().write(MyUtil.toJSONNull(response));
            return;
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean checkLogin(HttpServletRequest request){
        String userId = redisService.getAppCache(request.getHeader(Constants.TOKENID));
        if(userId != null){
            return true;
        }
        return false;
    }

    @Override
    public void destroy() {

    }
}
